package com.smec.moblie.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.smec.moblie.R;
import com.smec.moblie.adapter.AttachmentListAdapter;
import com.smec.moblie.adapter.FeedBackListAdapter;
import com.smec.moblie.bean.AttachmentBean;
import com.smec.moblie.bean.FeedbackBean;
import com.smec.moblie.bean.FeedbackContentBean;
import com.smec.moblie.bean.SelectListBean;
import com.smec.moblie.bean.TechHeadBean;
import com.smec.moblie.bean.TechnicalNoticeBean;
import com.smec.moblie.bean.TechnicalNoticeUpdateBean;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.control.MainControl;
import com.smec.moblie.control.PublicControl;
import com.smec.moblie.view.listView.MyListView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

import static com.smec.moblie.control.MainControl.submitFeedbackList;
import static com.smec.moblie.control.PublicControl.ImageToBuffer;

/**
 * Created by sunyubo on 2017/11/30.
 */

public class TechnicalNoticeDetailActivity extends BaseActivity {
    @BindView(R.id.imageview_back)
    ImageView imageviewBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.textViewNoticeNum)
    TextView textViewNoticeNum;
    @BindView(R.id.textViewEleType)
    TextView textViewEleType;
    @BindView(R.id.textViewEleContractNo)
    TextView textViewEleContractNo;
    @BindView(R.id.textViewEleNo)
    TextView textViewEleNo;
    @BindView(R.id.textViewCustomerName)
    TextView textViewCustomerName;
    @BindView(R.id.textViewSubject)
    TextView textViewSubject;
    @BindView(R.id.textViewCounttermeasure)
    TextView textViewCounttermeasure;
    @BindView(R.id.textViewAnnouncements)
    TextView textViewAnnouncements;
    @BindView(R.id.listViewAttachment)
    MyListView listViewAttachment;
    @BindView(R.id.listViewFeedback)
    MyListView listViewFeedback;
    @BindView(R.id.layoutProgress)
    RelativeLayout layoutProgress;
    @BindView(R.id.buttonRefresh)
    Button buttonRefresh;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.buttonSave)
    Button buttonSave;
    @BindView(R.id.buttonUpdate)
    Button buttonUpdate;

    private TechnicalNoticeBean technicalNoticeBean;
    private TechHeadBean techHeadBean;
    private FeedBackListAdapter feedBackListAdapter;
    private String tempImagePath = "";
    private int tempImagePosion = 0;
    private String updateType = "";
    private int a=0;
    private ArrayList<String> arrayList=new ArrayList<>();

    /****
     * 提示
     ****/
    private SVProgressHUD pd = null;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_technical_notice_detail);
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);//注册EventBus
        technicalNoticeBean = (TechnicalNoticeBean) getIntent().getSerializableExtra("technicalNoticeBean");
        pd = new SVProgressHUD(this);
    }

    @Override
    protected void getData() {
        try {
            techHeadBean = DataSupport.where("noticeId = ?", technicalNoticeBean.getNoticeId() + "").find(TechHeadBean.class).get(0);
            techHeadBean.setAttachment(DataSupport.where("noticeId = ?", techHeadBean.getNoticeId() + "").find(AttachmentBean.class));
            textViewNoticeNum.setText(techHeadBean.getNoticeNum());
            textViewEleType.setText(technicalNoticeBean.getEleType());
            textViewEleContractNo.setText(technicalNoticeBean.getEleContractNo());
            textViewEleNo.setText(technicalNoticeBean.getEleNo());
            textViewCustomerName.setText(technicalNoticeBean.getCustomerName());
            textViewSubject.setText(techHeadBean.getSubject());
            textViewCounttermeasure.setText(techHeadBean.getCounttermeasure());
            textViewAnnouncements.setText(techHeadBean.getAnnouncements());

            AttachmentListAdapter attachmentListAdapter = new AttachmentListAdapter(TechnicalNoticeDetailActivity.this);
            attachmentListAdapter.setList(techHeadBean.getAttachment());
            listViewAttachment.setAdapter(attachmentListAdapter);
            feedBackListAdapter = new FeedBackListAdapter(TechnicalNoticeDetailActivity.this, technicalNoticeBean.getStatus());
            listViewFeedback.setAdapter(feedBackListAdapter);
            if (DataSupport.where("itemId = ?", technicalNoticeBean.getItemId() + "").count(FeedbackBean.class) > 0) {
                EventBus.getDefault().post(new EventCenter.FeedBackListBackSuccess());
            } else {
                MainControl.getFeedbackList(technicalNoticeBean.getItemId(), TechnicalNoticeDetailActivity.this);
            }
            statusControl();

        } catch (Exception e) {
            Toast.makeText(this, "数据出现错误，加载失败，请在列表页下拉刷新", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    public void onClick(View v) {

    }

    private void statusControl() {
        if (technicalNoticeBean.getStatus().equals(COMPLETED)) {
            buttonSave.setVisibility(View.GONE);
            buttonUpdate.setVisibility(View.GONE);

        }
    }

    @OnClick({R.id.imageview_back, R.id.buttonRefresh, R.id.buttonUpdate, R.id.buttonSave})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imageview_back:
                finish();
                break;
            case R.id.buttonRefresh:
                MainControl.getFeedbackList(technicalNoticeBean.getItemId(), TechnicalNoticeDetailActivity.this);
                buttonRefresh.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                break;
            case R.id.buttonSave:
                new AlertView("提示", "确定保存数据到服务器吗？", "取消", new String[]{"确定"}, null, TechnicalNoticeDetailActivity.this,
                        AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int p) {
                        if (p == 0) {
                            TechnicalNoticeUpdateBean technicalNoticeUpdateBean = getUpdateData();
                            updateType = "SAVE";
                            technicalNoticeUpdateBean.setType(updateType);
                            submitFeedbackList(technicalNoticeUpdateBean, TechnicalNoticeDetailActivity.this);
                            pd.showWithStatus("数据正在上传...");
                        }
                    }
                }).show();
                break;
            case R.id.buttonUpdate:
                new AlertView("提示", "确定完成当前工单吗？", "取消", new String[]{"确定"}, null, TechnicalNoticeDetailActivity.this,
                        AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int p) {
                        if (p == 0) {
                            TechnicalNoticeUpdateBean technicalNoticeUpdateBean = getUpdateData();
                            if(a>0){
                                Toast.makeText(TechnicalNoticeDetailActivity.this,"当前还有必填项没填",Toast.LENGTH_SHORT).show();
                                a=0;
                            }else {
                                updateType = "SUBMIT";
                                technicalNoticeUpdateBean.setType(updateType);
                                submitFeedbackList(technicalNoticeUpdateBean, TechnicalNoticeDetailActivity.this);
                                pd.showWithStatus("数据正在上传...");
                            }
                        }
                    }
                }).show();
                break;
        }
    }

    private TechnicalNoticeUpdateBean getUpdateData() {
        TechnicalNoticeUpdateBean technicalNoticeUpdateBean = new TechnicalNoticeUpdateBean();
        List<TechnicalNoticeUpdateBean.FeedbacksBean> feedbacks = new ArrayList<>();
        List<TechnicalNoticeUpdateBean.PicturesBean> pictures = new ArrayList<>();
        for (FeedbackBean feedbackBean : feedBackListAdapter.getList()) {
            if (feedbackBean.getFeedbackType().equals(IMAGE)) {
                if (feedbackBean.getFeedbackContent().getSelectList() != null && feedbackBean.getFeedbackContent().getSelectList().size() > 1) {
                    for (SelectListBean selectListBean : feedbackBean.getFeedbackContent().getSelectList()) {
                        if (selectListBean.getImagePath() != null && !selectListBean.getImagePath().equals(ADDString) && selectListBean.getUpdateCode() == 0) {
                            TechnicalNoticeUpdateBean.PicturesBean picturesBean = new TechnicalNoticeUpdateBean.PicturesBean();
                            TechnicalNoticeUpdateBean.PicturesBean.BusinessBean businessBean = new TechnicalNoticeUpdateBean.PicturesBean.BusinessBean();
                            businessBean.setFeedbackId(feedbackBean.getFeedbackId());
                            picturesBean.setBusiness(businessBean);
                            picturesBean.setData(ImageToBuffer(selectListBean.getImagePath()));
                            pictures.add(picturesBean);
                        }
                    }
                }
            } else {
                TechnicalNoticeUpdateBean.FeedbacksBean feedbacksBean = new TechnicalNoticeUpdateBean.FeedbacksBean();
                feedbacksBean.setRequired(feedbackBean.getRequired());
                feedbacksBean.setTitle(feedbackBean.getTitle());
                if (feedbackBean.getFeedbackContent() != null && feedbackBean.getFeedbackContent().getContent() != null) {
                    feedbacksBean.setContent(feedbackBean.getFeedbackContent().getContent());
                }
                feedbacksBean.setFeedbackId(feedbackBean.getFeedbackId());
                feedbacks.add(feedbacksBean);
            }
        }
        for(int i=0;i<feedbacks.size();i++){
            if(feedbacks.get(i).getRequired().equals("Y")&&TextUtils.isEmpty(feedbacks.get(i).getContent())){
                a++;
                arrayList.add(feedbacks.get(i).getTitle());
            }
        }
        Log.w("aaaa", String.valueOf(a));
        technicalNoticeUpdateBean.setItemId(technicalNoticeBean.getItemId());
        technicalNoticeUpdateBean.setFeedbacks(feedbacks);
        technicalNoticeUpdateBean.setPictures(pictures);
        return technicalNoticeUpdateBean;
    }

    /**
     * 获取保养作业详情数据失败数据处理
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.FeedBackListBackSuccess event) {
        List<FeedbackBean> feedbackBeanList = DataSupport.where("itemId = ?", technicalNoticeBean.getItemId() + "").find(FeedbackBean.class);
        Log.i("debug", "~~itemId = " + technicalNoticeBean.getItemId());
        for (FeedbackBean feedbackBean : feedbackBeanList) {
            List<FeedbackContentBean> feedbackContentBeanList = DataSupport.where("feedbackId = ? AND itemId = ?", feedbackBean.getFeedbackId() + "", technicalNoticeBean.getItemId() + "").find(FeedbackContentBean.class);
            if (feedbackContentBeanList != null && feedbackContentBeanList.size() > 0) {
                FeedbackContentBean feedbackContentBean = feedbackContentBeanList.get(0);
                feedbackBean.setFeedbackContent(feedbackContentBean);
                List<SelectListBean> selectListBeanList = DataSupport.where("feedbackId = ? AND itemId = ?", feedbackBean.getFeedbackId() + "", technicalNoticeBean.getItemId() + "").find(SelectListBean.class);
                if (selectListBeanList != null && selectListBeanList.size() > 0) {
                    feedbackContentBean.setSelectList(selectListBeanList);
                }
            }

        }
        feedBackListAdapter.setList(feedbackBeanList);

        layoutProgress.setVisibility(View.GONE);
        listViewFeedback.setVisibility(View.VISIBLE);
    }

    /**
     * 获取保养作业详情数据失败数据处理
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.FeedBackListBackFailed event) {
        Toast.makeText(this, "获取保养作业详情失败，原因：" + event.getMsg(), Toast.LENGTH_SHORT).show();
        buttonRefresh.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 个性化保养-提交反馈项失败数据处理
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.submitFeedbackListFailed event) {
        Toast.makeText(this, "提交反馈项失败，原因：" + event.getMsg(), Toast.LENGTH_SHORT).show();
        if (pd.isShowing()) {
            pd.dismiss();
        }
    }

    /**
     * 提交工单成功数据处理
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.submitFeedbackListSuccess event) {
        Toast.makeText(this, "工单提交成功", Toast.LENGTH_SHORT).show();
        if (pd.isShowing()) {
            pd.dismiss();
        }
        if (updateType.equals("SUBMIT")) {
            technicalNoticeBean.setStatus(COMPLETED);
            TechnicalNoticeBean technicalNoticeBeanTemp = new TechnicalNoticeBean();
            technicalNoticeBeanTemp.setStatus(COMPLETED);
            technicalNoticeBeanTemp.update(technicalNoticeBean.getId());
//            technicalNoticeBean.save();
            EventBus.getDefault().post(new EventCenter.ReflashTechnicalNoticeList());
            TechnicalNoticeDetailActivity.this.finish();
        }

    }

    /**
     * 获取照片路径
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.GetImagePath event) {
        tempImagePath = event.getPath();
        tempImagePosion = event.getPosition();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 消息bus解注
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMERA_FEEDBACK_ADD) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap saveBitmap = BitmapFactory.decodeFile(tempImagePath, options);
                try {
                    PublicControl.saveFile(saveBitmap, tempImagePath);// 把压缩的图片保存到本地
                    SelectListBean selectListBean = new SelectListBean();
                    selectListBean.setFeedbackId(feedBackListAdapter.getItem(tempImagePosion).getFeedbackId());
                    selectListBean.setItemId(feedBackListAdapter.getItem(tempImagePosion).getItemId());
                    selectListBean.setImagePath(tempImagePath);
                    selectListBean.setUpdateCode(0);
                    selectListBean.save();
                    List<SelectListBean> selectListBeanList = feedBackListAdapter.getItem(tempImagePosion).getFeedbackContent().getSelectList();
                    selectListBeanList.remove(selectListBeanList.size() - 1);
                    selectListBeanList.add(selectListBean);
                    feedBackListAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap saveBitmap = BitmapFactory.decodeFile(tempImagePath, options);

                try {
                    PublicControl.saveFile(saveBitmap, tempImagePath);// 把压缩的图片保存到本地
                    SelectListBean selectListBean = feedBackListAdapter.getItem(tempImagePosion).getFeedbackContent().getSelectList().get(requestCode - CAMERA_FEEDBACK_RESHOT);
                    selectListBean.setImagePath(tempImagePath);
                    selectListBean.setUpdateCode(0);
                    selectListBean.setValue("");
                    selectListBean.save();

                    feedBackListAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
